/*
 * XXX
 */

package edu.uhcl.csci4838.group3.view;

import java.text.DecimalFormat;
import java.text.Format;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

import edu.uhcl.csci4838.group3.R;
import edu.uhcl.csci4838.group3.calc.CategoryException;
import edu.uhcl.csci4838.group3.calc.GradeCal;
import edu.uhcl.csci4838.group3.calc.MissingInfoException;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorCourse;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorCourseCategoryWeight;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorGradingScaleRange;
import edu.uhcl.csci4838.group3.database.BackpackEduDatabaseHelper.CursorTask;
import edu.uhcl.csci4838.group3.database.info.CourseCategoryWeight;
import edu.uhcl.csci4838.group3.database.info.GradingScaleRange;
import edu.uhcl.csci4838.group3.database.info.Task;
import edu.uhcl.csci4838.group3.dto.Category;
import edu.uhcl.csci4838.group3.dto.Course;
import edu.uhcl.csci4838.group3.dto.GradingScale;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.InputType;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.TableRow;

/**
 * XXX
 * 
 * @author Chris Waguespack
 */
public class GradesActivity extends Activity {
	
	// A tablerow that knows its type
	private static class CustomLinearLayout extends LinearLayout {
		
		public static enum Type {
			CATEGORY,
			TASK,
			NONE
		};
		
		public CustomLinearLayout(Context context) {
			super(context);
		}
		
		private Type type;
		
		public Type getType() {
			return this.type;
		}
		
		public void setType(Type type) {
			this.type = type;
		}
		
	}
	
	// db
	private BackpackEduDatabaseHelper db;
	
	// Cursors
	private CursorCourseCategoryWeight cats;
	private CursorTask tasks;
	private CursorCourseCategoryWeight ccw;
	
	// Layouts
	private LinearLayout lloWhatIf;
	// private LinearLayout lloFinalGrades;
	// private RadioGroup radioGroup;
	// private RadioButton radioWhatIf;
	// private RadioButton radioFinalGrades;
	// private Spinner spinner;
	private Button reCalculate, clear;
	private TextView tvCurrentAverage;
	// private TextView tvFinal;
	
	// Views' Listeners
	// private View.OnClickListener radioButtonOnClickListener;
	// private OnItemSelectedListener spinnerOnItemSelectedListenser;
	private View.OnClickListener buttonRerunOnClickListener;
	private View.OnClickListener buttonClearOnClickListener;
	
	// Adapters
	// private ArrayAdapter<CharSequence> adapter;
	
	// Colors and Formattings
	private int colorCategory;
	private int colorTask;
	private int colorTextViewShadowLayer;
	private int colorCurrentAverage;
	private int pTvLeft, pTvTop, pTvRight, pTvBottom;
	private int deviceWidth;
	
	// Misc.
	private NumberFormat format;
	private long courseId;
	private Category catFinal;
	private edu.uhcl.csci4838.group3.dto.Task taskFinal;
	
	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		this.setContentView(R.layout.activity_list_grades);
		
		// Calling intent
		final Intent callingIntent = this.getIntent();
		courseId = callingIntent.getLongExtra(this.getString(R.string.intent_extra_courseId),
				-1);
		
		// Get display's width
		Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
		deviceWidth = display.getWidth();
		
		// Open db connection
		db = new BackpackEduDatabaseHelper(this);
		
		// Get cursors
		ContentValues map = new ContentValues();
		map.put(Task.COURSE_ID,
				courseId);
		tasks = db.getTask(map,
				new String[] { Task.CATEGORY_NAME, Task.NAME },
				true);
		map.clear();
		map.put(CourseCategoryWeight.COURSE_ID,
				courseId);
		ccw = db.getCourseCategoryWeight(map,
				new String[] { CourseCategoryWeight.CATEGORY_NAME },
				true);
		
		// Reference the xml layouts
		lloWhatIf = (LinearLayout) findViewById(R.id.lloWhatIf);
		// lloFinalGrades = (LinearLayout) findViewById(R.id.lloFinalGrades);
		// radioGroup = (RadioGroup) findViewById(R.id.radioWhatIfFinalGrades);
		// radioWhatIf = (RadioButton) findViewById(R.id.radioWhatIf);
		// radioFinalGrades = (RadioButton) findViewById(R.id.radioFinalGrades);
		// spinner = (Spinner) findViewById(R.id.spinnerTasks);
		
		// Initialize views
		// tvFinal = new TextView(this);
		// lloFinalGrades.addView(tvFinal);
		reCalculate = new Button(this);
		clear = new Button(this);
		reCalculate.setWidth(deviceWidth / 2);
		clear.setWidth(deviceWidth / 2);
		reCalculate.setText("Recalculate");
		clear.setText("Clear");
		
		// Set up adapter
		// adapter = new ArrayAdapter<CharSequence>(this,
		// android.R.layout.simple_spinner_item);
		// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// spinner.setAdapter(adapter);
		
		// Initialize Formatter
		format = new DecimalFormat("0.00");
		
		// Initialize Listeners
		buttonClearOnClickListener = new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				fillWhatIf();
				Course course = constructCourseDtoForWhatIf();
				try {
					Double average = GradeCal.runningCourseAverage(course);
					tvCurrentAverage.setText("Your running average is: "
							+ format.format(average)
							+ " %");
				} catch (CategoryException ex) {
					tvCurrentAverage.setText("Please check your input!");
				}
			}
		};
		
		buttonRerunOnClickListener = new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Course course = constructCourseDtoForWhatIf();
				try {
					
					Double average = GradeCal.runningCourseAverage(course);
					tvCurrentAverage.setText("Your running average is: "
							+ format.format(average)
							+ " %");
				} catch (CategoryException ex) {
					tvCurrentAverage.setText("Please check your input!");
				}
				
			}
		};
		
		// radioButtonOnClickListener = new View.OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// int selectRadioButton = radioGroup.getCheckedRadioButtonId();
		// if (selectRadioButton == R.id.radioWhatIf) {
		//
		// // Correct visibility
		// lloFinalGrades.setVisibility(View.GONE);
		// spinner.setVisibility(View.GONE);
		// lloWhatIf.setVisibility(View.VISIBLE);
		// } else {
		//
		// // Correct visibility
		// lloWhatIf.setVisibility(View.GONE);
		// spinner.setVisibility(View.VISIBLE);
		// lloFinalGrades.setVisibility(View.VISIBLE);
		// }
		// }
		// };
		// spinnerOnItemSelectedListenser = new OnItemSelectedListener() {
		// @Override
		// public void onItemSelected(AdapterView<?> arg0,
		// View arg1,
		// int arg2,
		// long arg3) {
		//
		// if (spinner.getCount() > 1
		// && spinner.getSelectedItemPosition() != 0) {
		//
		// // Get course dto
		// Course course = constructCourseDtoForFinal();
		//
		// Map<String, Double> map = new HashMap<String, Double>();
		// try {
		// map = GradeCal.gradeNeededOnFinal(course,
		// taskFinal);
		// for (Map.Entry<String, Double> entry : map.entrySet()) {
		// tvFinal.setText(entry.getKey()
		// + "\t"
		// + entry.getValue()
		// + "\n");
		// }
		//
		// } catch (MissingInfoException ex) {
		//
		// } catch (CategoryException ex) {
		//
		// }
		// } else if (spinner.getCount() == 1) {
		//
		// tvFinal.setText("No task to select");
		//
		// } else if (spinner.getSelectedItemPosition() == 0) {
		//
		// tvFinal.setText("Select a task to be the final exam to see the final grades needed");
		//
		// }
		//
		// }
		//
		// @Override
		// public void onNothingSelected(AdapterView<?> arg0) {
		// // Empty
		// }
		// };
		
		// Initialize formatting values
		pTvLeft = 0;
		pTvTop = 5;
		pTvRight = 0;
		pTvBottom = 5;
		colorTextViewShadowLayer = Color.parseColor("#0078AE");
		colorCurrentAverage = Color.parseColor("#49AED0");
		colorCategory = Color.parseColor("#FDB913");
		colorTask = Color.parseColor("#00B259");
		colorTextViewShadowLayer = Color.parseColor("#0078AE");
		
		// Initialize dtos
		catFinal = new Category();
		taskFinal = new edu.uhcl.csci4838.group3.dto.Task();
		
		// Register Listeners
		// radioWhatIf.setOnClickListener(radioButtonOnClickListener);
		// radioFinalGrades.setOnClickListener(radioButtonOnClickListener);
		// spinner.setOnItemSelectedListener(spinnerOnItemSelectedListenser);
		clear.setOnClickListener(buttonClearOnClickListener);
		reCalculate.setOnClickListener(buttonRerunOnClickListener);
		
		// fill the tables
		fillWhatIf();
		// fillFinalGrades();
		
		// Calculate running average
		Course course = constructCourseDtoForWhatIf();
		try {
			Double average = GradeCal.runningCourseAverage(course);
			tvCurrentAverage.setText("Your running average is: "
					+ format.format(average)
					+ " %");
		} catch (CategoryException ex) {
			tvCurrentAverage.setText("Please check your input!");
		}
		
	}
	
	// fillWhatIf()
	private void fillWhatIf() {
		
		// Remove all views from what-if layout
		lloWhatIf.removeAllViews();
		lloWhatIf.setPadding(0, 5, 0, 0);
		
		// Initializing views
		CustomLinearLayout cllo = new CustomLinearLayout(this);
		TextView tv = new TextView(this);
		
		if (tasks.getCount() < 1) {
			
			// Formatting views
			cllo.setGravity(Gravity.CENTER_VERTICAL);
			
			// Adding the view to the table
			tv.setText("No grades to display");
			tv.setTextColor(Color.WHITE);
			cllo.addView(tv);
			lloWhatIf.addView(cllo);
			
		} else {
			
			// Add a separation line
			View v = new View(this);
			v.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
					2));
			v.setBackgroundColor(Color.WHITE);
			lloWhatIf.addView(v);
			
			// Formatting the current average row
			cllo.setGravity(Gravity.CENTER);
			cllo.setType(CustomLinearLayout.Type.NONE);
			tv.setTextColor(Color.WHITE);
			tv.setWidth(deviceWidth);
			tv.setGravity(Gravity.CENTER);
			tv.setBackgroundColor(colorCurrentAverage);
			tv.setPadding(pTvLeft,
					pTvTop + 3,
					pTvRight,
					pTvBottom + 3);
			tv.setShadowLayer(4,
					3,
					3,
					colorTextViewShadowLayer);
			tv.setTypeface(null,
					1);
			tv.setText("Your current running average is: %");
			tvCurrentAverage = tv;
			
			// Add the current avg. bar
			cllo.addView(tv);
			lloWhatIf.addView(cllo);
			
			// Add a separation line
			v = new View(this);
			v.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
					2));
			v.setBackgroundColor(Color.WHITE);
			lloWhatIf.addView(v);
			
			// Add the refresh and rerun buttons
			cllo = new CustomLinearLayout(this);
			cllo.setGravity(Gravity.CENTER);
			cllo.setType(CustomLinearLayout.Type.NONE);
			cllo.setPadding(0,
					5,
					0,
					3);
			
			if (reCalculate.getParent() != null) {
				((LinearLayout) reCalculate.getParent()).removeAllViews();
			}
			if (clear.getParent() != null) {
				((LinearLayout) clear.getParent()).removeAllViews();
			}
			
			cllo.addView(reCalculate);
			cllo.addView(clear);
			lloWhatIf.addView(cllo);
			
			// Add a separation line
			v = new View(this);
			v.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
					2));
			v.setBackgroundColor(Color.WHITE);
			lloWhatIf.addView(v);
			
			// Move the ccw cursor to the first position
			ccw.moveToPosition(0);
			tasks.moveToPosition(0);
			
			// Add a category bar
			addCategoryBar();
			
			// Add all the tasks for the categories
			for (int i = 0; i < tasks.getCount(); i++) {
				
				// Move the task cursor to the correct position
				tasks.moveToPosition(i);
				
				// Add a category bar if needed
				if (tasks.getColCategoryName()
						.compareTo(ccw.getColCategoryName()) != 0) {
					addCategoryBar();
				}
				
				// Add the current task to the linear layout
				addTaskBar();
				
			}
			
		}
		
	}
	
	// fillFinalGrades()
	// private void fillFinalGrades() {
	//
	// // Remove all tasks from spinner
	// adapter.clear();
	//
	// // Populate the spinner adapter
	// if (tasks.getCount() > 0) {
	//
	// adapter.add("Select your final exam");
	//
	// for (int i = 0; i < tasks.getCount(); i++) {
	//
	// // move the cursor to the correct position
	// tasks.moveToPosition(i);
	//
	// adapter.add(tasks.getColName());
	// }
	//
	// // Add a text box to show results
	//
	// } else {
	//
	// adapter.add("No tasks to select");
	//
	// }
	// }
	
	// addCategoryBar()
	private void addCategoryBar() {
		
		// Move ccw cursor to the current task's category
		while (ccw.getColCategoryName()
				.compareTo(tasks.getColCategoryName()) != 0) {
			ccw.moveToPosition(ccw.getPosition() + 1);
		}
		
		// Initializing views
		CustomLinearLayout cllo = new CustomLinearLayout(this);
		TextView tv = new TextView(this);
		TextView tvPercent = new TextView(this);
		EditText etCategoryWeight = new EditText(this);
		
		// Formatting views
		cllo.setGravity(Gravity.CENTER);
		cllo.setType(CustomLinearLayout.Type.CATEGORY);
		cllo.setBackgroundColor(colorCategory);
		cllo.setPadding(pTvLeft,
				pTvTop,
				pTvRight,
				pTvBottom);
		int etWidth = deviceWidth / 4;
		
		etCategoryWeight.setInputType(InputType.TYPE_CLASS_NUMBER
				| InputType.TYPE_NUMBER_FLAG_DECIMAL);
		etCategoryWeight.setWidth(etWidth);
		etCategoryWeight.setSingleLine();
		etCategoryWeight.setText(ccw.getColWeight() == null
				? ""
				: ccw.getColWeight()
						.toString());
		
		tv.setGravity(Gravity.CENTER);
		tv.setTextColor(Color.WHITE);
		tv.setShadowLayer(4,
				3,
				3,
				colorTextViewShadowLayer);
		tv.setTypeface(null,
				1);
		tv.setText(Html.fromHtml("<big>"
				+ ccw.getColCategoryName()
				+ "  "
				+ "</big>"));
		
		tvPercent.setTextColor(Color.WHITE);
		tvPercent.setText(Html.fromHtml("<big>"
				+ "  %"
				+ "</big>"));
		
		// Add views to the what-if linear layout
		cllo.addView(tv);
		cllo.addView(etCategoryWeight);
		cllo.addView(tvPercent);
		lloWhatIf.addView(cllo);
		
		// Add a separation line
		View v = new View(this);
		v.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				2));
		v.setBackgroundColor(Color.WHITE);
		lloWhatIf.addView(v);
	}
	
	// addTaskBar()
	private void addTaskBar() {
		
		// Initializing views
		CustomLinearLayout cllo = new CustomLinearLayout(this);
		TextView tv = new TextView(this);
		
		// Formatting views
		cllo.setGravity(Gravity.CENTER_VERTICAL);
		cllo.setType(CustomLinearLayout.Type.NONE);
		cllo.setBackgroundColor(colorTask);
		tv.setPadding(0,
				pTvTop,
				0,
				0);
		
		tv.setTextColor(Color.WHITE);
		tv.setShadowLayer(4,
				3,
				3,
				colorTextViewShadowLayer);
		tv.setTypeface(null,
				1);
		tv.setText("  "
				+ tasks.getColName());
		int etWidth = deviceWidth / 4;
		
		// Add views to the table what-if
		cllo.addView(tv);
		lloWhatIf.addView(cllo);
		
		// Initializing views
		cllo = new CustomLinearLayout(this);
		TextView tvPts = new TextView(this);
		TextView tvPercent = new TextView(this);
		TextView tvSlash = new TextView(this);
		EditText etReceivedGrade = new EditText(this);
		EditText etMaxGrade = new EditText(this);
		EditText etWeightOverride = new EditText(this);
		
		// Formatting views
		cllo.setGravity(Gravity.CENTER_VERTICAL);
		cllo.setType(CustomLinearLayout.Type.TASK);
		cllo.setBackgroundColor(colorTask);
		cllo.setPadding(pTvLeft + 2,
				pTvTop,
				pTvRight,
				pTvBottom + 3);
		
		etReceivedGrade.setInputType(InputType.TYPE_CLASS_NUMBER
				| InputType.TYPE_NUMBER_FLAG_DECIMAL);
		etReceivedGrade.setWidth(etWidth);
		etReceivedGrade.setSingleLine();
		etReceivedGrade.setText(tasks.getColReceivedGrade() == null
				? ""
				: tasks.getColReceivedGrade()
						.toString());
		
		etMaxGrade.setInputType(InputType.TYPE_CLASS_NUMBER
				| InputType.TYPE_NUMBER_FLAG_DECIMAL);
		etMaxGrade.setWidth(etWidth);
		etMaxGrade.setSingleLine();
		etMaxGrade.setText(tasks.getColMaxGrade() == null
				? ""
				: tasks.getColMaxGrade()
						.toString());
		
		etWeightOverride.setInputType(InputType.TYPE_CLASS_NUMBER
				| InputType.TYPE_NUMBER_FLAG_DECIMAL);
		etWeightOverride.setWidth(etWidth);
		etWeightOverride.setSingleLine();
		etWeightOverride.setText(tasks.getColWeightOverride() == null
				? ""
				: tasks.getColWeightOverride()
						.toString());
		
		tvPts.setTextColor(Color.WHITE);
		tvPts.setShadowLayer(4,
				3,
				3,
				colorTextViewShadowLayer);
		tvPts.setTypeface(null,
				1);
		tvPts.setText(" pts   ");
		
		tvPercent.setTextColor(Color.WHITE);
		tvPercent.setShadowLayer(4,
				3,
				3,
				colorTextViewShadowLayer);
		tvPercent.setTypeface(null,
				1);
		tvPercent.setText(" %");
		
		tvSlash.setTextColor(Color.WHITE);
		tvSlash.setShadowLayer(4,
				3,
				3,
				colorTextViewShadowLayer);
		tvSlash.setTypeface(null,
				1);
		tvSlash.setText(" / ");
		
		// Add views to the table what-if
		cllo.addView(etReceivedGrade);
		cllo.addView(tvSlash);
		cllo.addView(etMaxGrade);
		cllo.addView(tvPts);
		cllo.addView(etWeightOverride);
		cllo.addView(tvPercent);
		lloWhatIf.addView(cllo);
		
		// Add a separation line
		View v = new View(this);
		v.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
				2));
		v.setBackgroundColor(Color.WHITE);
		lloWhatIf.addView(v);
	}
	
	// constructCourseDtoForFinal()
	// private Course constructCourseDtoForFinal() {
	//
	// // dtos
	// Course courseDto = new Course();
	// Category catDto = new Category();
	// GradingScale gScaleDto = new GradingScale();
	// edu.uhcl.csci4838.group3.dto.Task taskDto;
	//
	// // cursors
	// ContentValues criteria = new ContentValues();
	// criteria.put(edu.uhcl.csci4838.group3.database.info.Course.ID,
	// courseId);
	// CursorCourse courses = db.getCourse(criteria,
	// null,
	// true);
	// criteria.clear();
	// criteria.put(GradingScaleRange.NAME,
	// courses.getColGradeScaleName());
	// CursorGradingScaleRange ranges = db.getGradingScaleRange(criteria,
	// null,
	// true);
	//
	// // misc.
	// ArrayList<Category> catDtos = new ArrayList<Category>();
	// ArrayList<edu.uhcl.csci4838.group3.dto.Task> taskDtos;
	// Map<String, Double> map = new HashMap<String, Double>();
	//
	// // Move the cursor to the correct position
	// tasks.moveToPosition(0);
	//
	// // Move the ccw cursor to the correct row to avoid cat with empty tasks
	// for (int i = 0; i < ccw.getCount(); i++) {
	//
	// // Move the cursor to the correct position
	// ccw.moveToPosition(i);
	// if (ccw.getColCategoryName()
	// .compareTo(tasks.getColCategoryName()) == 0) {
	// break;
	// }
	// }
	//
	// catDto = new Category();
	// catFinal = new Category();
	// catDto.setWeight(ccw.getColWeight());
	// catDto.setCourse(courseDto);
	// catFinal.setWeight(ccw.getColWeight());
	// catFinal.setCourse(courseDto);
	//
	// // Get all the tasks for this cat
	// taskDtos = new ArrayList<edu.uhcl.csci4838.group3.dto.Task>();
	// for (int i = 0; i < tasks.getCount(); i++) {
	//
	// // Move the cursor to the correct position
	// tasks.moveToPosition(i);
	//
	// if (ccw.getColCategoryName()
	// .compareTo(tasks.getColCategoryName()) == 0) {
	//
	// // Initialize the task dto
	// taskDto = new edu.uhcl.csci4838.group3.dto.Task();
	//
	// // Set the attributes for the task dto
	// taskDto.setCategory(catDto);
	// taskDto.setReceivedGrade(tasks.getColReceivedGrade());
	// taskDto.setMaxGrade(tasks.getColMaxGrade());
	// taskDto.setWeightOverride(tasks.getColWeightOverride());
	//
	// // Add the task dto to the task dto array
	// taskDtos.add(taskDto);
	//
	// // Save the selected task
	// if (tasks.getPosition() == (spinner.getSelectedItemPosition() - 1)) {
	//
	// taskFinal = new edu.uhcl.csci4838.group3.dto.Task();
	// taskFinal.setCategory(catDto);
	// taskFinal.setReceivedGrade(tasks.getColReceivedGrade());
	// taskFinal.setMaxGrade(tasks.getColMaxGrade());
	// taskFinal.setWeightOverride(tasks.getColWeightOverride());
	//
	// taskFinal.setCategory(catFinal);
	//
	// }
	// } else {
	// break;
	// }
	//
	// }
	//
	// // add the tasks array to the cat
	// catDto.setTasks(taskDtos);
	// catFinal.setTasks(taskDtos);
	// catDtos.add(catDto);
	//
	// // Get grade scale
	// for (int i = 0; i < ranges.getCount(); i++) {
	//
	// ranges.moveToPosition(i);
	// map.put(ranges.getColLetterGrade(),
	// ranges.getColMinValue());
	//
	// }
	//
	// gScaleDto.setName(courses.getColGradeScaleName());
	// gScaleDto.setScale(map);
	//
	// courseDto.setCategories(catDtos);
	// courseDto.setName(courses.getColName());
	// courseDto.setGradingScale(gScaleDto);
	//
	// // close cursors
	// courses.close();
	// ranges.close();
	//
	// return courseDto;
	// }
	
	// constructCourseDtoForWhatIf()
	private Course constructCourseDtoForWhatIf() {
		
		// dtos
		Course courseDto = new Course();
		Category catDto = new Category();
		GradingScale gScaleDto = new GradingScale();
		edu.uhcl.csci4838.group3.dto.Task taskDto;
		
		// cursors
		ContentValues criteria = new ContentValues();
		criteria.put(edu.uhcl.csci4838.group3.database.info.Course.ID,
				courseId);
		CursorCourse courses = db.getCourse(criteria,
				null,
				true);
		criteria.clear();
		criteria.put(GradingScaleRange.NAME,
				courses.getColGradeScaleName());
		CursorGradingScaleRange ranges = db.getGradingScaleRange(criteria,
				null,
				true);
		
		// misc.
		ArrayList<Category> catDtos = new ArrayList<Category>();
		ArrayList<edu.uhcl.csci4838.group3.dto.Task> taskDtos;
		Map<String, Double> map = new HashMap<String, Double>();
		
		// construct cat array list
		for (int i = 0; i < lloWhatIf.getChildCount();) {
			
			if (lloWhatIf.getChildAt(i)
					.getClass() == CustomLinearLayout.class) {
				if (((CustomLinearLayout) lloWhatIf.getChildAt(i)).getType() == CustomLinearLayout.Type.CATEGORY) {
					
					catDto = new Category();
					Double categoryWeight;
					
					EditText et = (EditText) ((CustomLinearLayout) lloWhatIf.getChildAt(i)).getChildAt(1);
					if (et.getText()
							.toString()
							.trim()
							.compareTo("") != 0) {
						categoryWeight = Double.parseDouble(et.getText()
								.toString()
								.trim());
						
					} else {
						categoryWeight = null;
					}
					
					catDto.setWeight(categoryWeight);
					catDto.setCourse(courseDto);
					
					// Get all the tasks for this cat
					taskDtos = new ArrayList<edu.uhcl.csci4838.group3.dto.Task>();
					i++;
					while (i < lloWhatIf.getChildCount()) {
						
						if (lloWhatIf.getChildAt(i)
								.getClass() == CustomLinearLayout.class) {
							if (((CustomLinearLayout) lloWhatIf.getChildAt(i)).getType() == CustomLinearLayout.Type.TASK) {
								
								// Add the task to the task array
								
								EditText receivedGrade = (EditText) ((CustomLinearLayout) lloWhatIf.getChildAt(i)).getChildAt(0);
								EditText maxGrade = (EditText) ((CustomLinearLayout) lloWhatIf.getChildAt(i)).getChildAt(2);
								EditText weightOverride = (EditText) ((CustomLinearLayout) lloWhatIf.getChildAt(i)).getChildAt(4);
								
								taskDto = new edu.uhcl.csci4838.group3.dto.Task();
								taskDto.setCategory(catDto);
								
								if (receivedGrade.getText()
										.toString()
										.trim()
										.compareTo("") != 0) {
									taskDto.setReceivedGrade(Double.parseDouble(receivedGrade.getText()
											.toString()
											.trim()));
									
								} else {
									taskDto.setReceivedGrade(null);
								}
								
								if (maxGrade.getText()
										.toString()
										.trim()
										.compareTo("") != 0) {
									taskDto.setMaxGrade(Double.parseDouble(maxGrade.getText()
											.toString()
											.trim()));
									
								} else {
									taskDto.setMaxGrade(null);
								}
								
								if (weightOverride.getText()
										.toString()
										.trim()
										.compareTo("") != 0) {
									
									taskDto.setWeightOverride(Double.parseDouble(weightOverride.getText()
											.toString()
											.trim()));
									
								} else {
									taskDto.setWeightOverride(null);
								}
								
								i++;
								taskDtos.add(taskDto);
								
							} else if (((CustomLinearLayout) lloWhatIf.getChildAt(i)).getType() == CustomLinearLayout.Type.CATEGORY) {
								break;
							} else {
								i++;
							}
						} else {
							i++;
						}
						
					}
					
					// add the tasks array to the cat
					catDto.setTasks(taskDtos);
					catDtos.add(catDto);
					
				} else {
					i++;
				}
				
			} else {
				i++;
			}
			
		}
		
		// Get grade scale
		for (int i = 0; i < ranges.getCount(); i++) {
			
			ranges.moveToPosition(i);
			map.put(ranges.getColLetterGrade(),
					ranges.getColMinValue());
			
		}
		
		gScaleDto.setName(courses.getColGradeScaleName());
		gScaleDto.setScale(map);
		
		courseDto.setCategories(catDtos);
		courseDto.setName(courses.getColName());
		courseDto.setGradingScale(gScaleDto);
		
		// close cursors
		courses.close();
		ranges.close();
		
		return courseDto;
	}
	
	// isCursorsChanged()
	private boolean isCursorsChanged() {
		boolean result = false;
		
		// Get new cursors
		ContentValues map = new ContentValues();
		map.put(Task.COURSE_ID,
				courseId);
		CursorTask tasksNew = db.getTask(map,
				new String[] { Task.CATEGORY_NAME, Task.NAME },
				true);
		map.clear();
		map.put(CourseCategoryWeight.COURSE_ID,
				courseId);
		CursorCourseCategoryWeight ccwNew = db.getCourseCategoryWeight(map,
				new String[] { CourseCategoryWeight.CATEGORY_NAME },
				true);
		
		// Compare with old cursors
		if (tasks.getCount() != tasksNew.getCount()
				|| ccw.getCount() != ccwNew.getCount()) {
			
			result = true;
			
		} else {
			
			for (int i = 0; i < tasks.getCount(); i++) {
				
				// Move cursors to the correct position
				tasks.moveToPosition(i);
				tasksNew.moveToPosition(i);
				
				if (tasks.getColName()
						.compareTo(tasksNew.getColName()) != 0) {
					result = true;
					break;
				}
				
				if (tasks.getColReceivedGrade() != null
						&& tasksNew.getColReceivedGrade() != null) {
					if (tasks.getColReceivedGrade()
							.doubleValue() != tasksNew.getColReceivedGrade()
							.doubleValue()) {
						result = true;
						break;
					}
				} else if (!(tasks.getColReceivedGrade() == null && tasksNew.getColReceivedGrade() == null)) {
					result = true;
					break;
				}
				
				if (tasks.getColMaxGrade() != null
						&& tasksNew.getColMaxGrade() != null) {
					if (tasks.getColMaxGrade()
							.doubleValue() != tasksNew.getColMaxGrade()
							.doubleValue()) {
						result = true;
						break;
					}
				} else if (!(tasks.getColMaxGrade() == null && tasksNew.getColMaxGrade() == null)) {
					result = true;
					break;
				}
				
				if (tasks.getColWeightOverride() != null
						&& tasksNew.getColWeightOverride() != null) {
					if (tasks.getColWeightOverride()
							.doubleValue() != tasksNew.getColWeightOverride()
							.doubleValue()) {
						result = true;
						break;
					}
				} else if (!(tasks.getColWeightOverride() == null && tasksNew.getColWeightOverride() == null)) {
					result = true;
					break;
				}
			}
			
			if (!result) {
				
				for (int i = 0; i < ccw.getCount(); i++) {
					
					// Move cursors to the correct position
					ccw.moveToPosition(i);
					ccwNew.moveToPosition(i);
					
					if (ccw.getColCategoryName()
							.compareTo(ccwNew.getColCategoryName()) != 0) {
						result = true;
						break;
					}
					
					if (ccw.getColWeight() != null
							&& ccwNew.getColWeight() != null) {
						if (ccw.getColWeight()
								.doubleValue() != ccwNew.getColWeight()
								.doubleValue()) {
							result = true;
							break;
						}
					} else if (!(ccw.getColWeight() == null && ccwNew.getColWeight() == null)) {
						result = true;
						break;
					}
				}
			}
		}
		
		tasksNew.close();
		ccwNew.close();
		return result;
	}
	
	@Override
	protected void onDestroy() {
		db.close();
		tasks.close();
		ccw.close();
		super.onDestroy();
	}
	
	// onResume()
	@Override
	protected void onResume() {
		super.onResume();
		
		if (isCursorsChanged()) {
			
			// Log.d("isCursorsChanged()",
			// "isCursorsChanged() = true");
			
			// close cursors
			ccw.close();
			tasks.close();
			
			// Get new cursors
			ContentValues map = new ContentValues();
			map.put(Task.COURSE_ID,
					courseId);
			tasks = db.getTask(map,
					new String[] { Task.CATEGORY_NAME, Task.NAME },
					true);
			map.clear();
			map.put(CourseCategoryWeight.COURSE_ID,
					courseId);
			ccw = db.getCourseCategoryWeight(map,
					new String[] { CourseCategoryWeight.CATEGORY_NAME },
					true);
			
			// refill
			fillWhatIf();
			// fillFinalGrades();
			
		}
		
	}
}
